package com.htfyun.roobofactory.factorytest;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.AppCompatTextView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.htfyun.roobofactory.BaseActivity;
import com.htfyun.roobofactory.R;
import com.htfyun.roobofactory.config.AppConfig;

/**
 * Created by sst on 2018/7/7.
 */

public class TPTestActivity extends BaseActivity {

    public static final int VIEW_MIN_WIDTH = 80;
    public static final int VIEW_MIN_HEIGHT = 80;

    private RelativeLayout parentContainer;

    private boolean mViewItemsCreated = false;

    private Rect rectTemp = new Rect();
    private boolean isAllItemGone = false;


    private Context mContext;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_factorytest_tp);

        mContext = this;

        parentContainer = (RelativeLayout) findViewById(R.id.touch_draw_root_layout);

        findViewById(R.id.btnFail).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(RESULT_CANCELED);

                ActivityCompat.finishAfterTransition(getActivity());
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();

        setTouchShowEnabled(true);


    }

    @Override
    protected void onPause() {
        super.onPause();

        setTouchShowEnabled(false);

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            createAllViewItems();
        }
    }


    /*
     * 20170418,this needs SystemUI privilige.
     */
    private void setTouchShowEnabled(boolean enabled) {

        try {

            Settings.System.putInt(getContentResolver(),
                /* Settings.System.POINTER_LOCATION*/
                    AppConfig.POINTER_LOCATION, enabled ? 1 : 0);
            Settings.System.putInt(getContentResolver(),
                /*Settings.System.SHOW_TOUCHES*/
                    AppConfig.SHOW_TOUCHES, enabled ? 1 : 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createAllViewItems(){

        if( mViewItemsCreated ) return ;
        mViewItemsCreated = true;

        CreateViewItems(mContext, parentContainer);
    }

    private void CreateViewItems(Context context, RelativeLayout parent) {

        parent.removeAllViews();

        int w = parent.getWidth();
        int h = parent.getHeight();

        Log.e(TAG, "parent:w=" + w + ",h=" + h);
        if (w == 0 || h == 0) {
            DisplayMetrics dm = new DisplayMetrics();
            Display display = getWindowManager().getDefaultDisplay();

            display.getMetrics(dm);
            w = dm.widthPixels;
            h = dm.heightPixels;
        }

        float viewW = VIEW_MIN_WIDTH;
        float viewH = VIEW_MIN_HEIGHT;
        int itemViewCountHorizontal = w / VIEW_MIN_WIDTH;
        int itemViewCountVertical = h / VIEW_MIN_HEIGHT;
        float deltaW = 1.0f * w % VIEW_MIN_WIDTH;
        float deltaH = 1.0f * h % VIEW_MIN_HEIGHT;

        viewW += deltaW / itemViewCountHorizontal;
        viewH += deltaH / itemViewCountVertical;

        int index = 0;

        for (int i = 0; i < itemViewCountVertical; i++) {

            if (i == 0 || i == (itemViewCountVertical / 2) || i == (itemViewCountVertical - 1)) {

                for (int j = 0; j < itemViewCountHorizontal; j++) {

                    TouchViewItem v = new TouchViewItem(context,
                            j * viewW, i * viewH,
                            (int) viewW, (int) viewH, index++);
                    parent.addView(v);

                }
            } else {

                for (int j = 0; j < 3; j++) {

                    float x = 0;
                    if (j == 1) {
                        x = (j * (itemViewCountHorizontal / 2)) * viewW;

                    } else if (j == 2) {
                        x = ((itemViewCountHorizontal - 1)) * viewW;
                    }

                    TouchViewItem v = new TouchViewItem(context,
                            x, i * viewH,
                            (int) viewW, (int) viewH, index++);

                    parent.addView(v);
                }
            }
        }

    }

    private void tpTestPassed() {

        Toast.makeText(mContext, R.string.tp_passed, Toast.LENGTH_SHORT).show();

        setResult(RESULT_OK);
        ActivityCompat.finishAfterTransition(getActivity());

//        parentContainer.removeAllViews();
//
//        Button btn = new Button(mContext);
//        btn.setTextColor(Color.BLACK);
//        btn.setGravity(Gravity.CENTER);
//        btn.setElevation(0.0f);
//
//        btn.setText(R.string.test_result_pass);
//
//        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        lp.setMarginStart(20);
//        lp.setMarginEnd(20);
//        lp.addRule(RelativeLayout.CENTER_IN_PARENT);
//        parentContainer.addView(btn, lp);
//
//        btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                Log.e(TAG, "btn clicked...");
//
//                setResult(RESULT_OK);
//                ActivityCompat.finishAfterTransition(getActivity());
//            }
//        });
    }

    private void checkTouchView(int x , int y){

        boolean allGone = true;
        int count = parentContainer.getChildCount();
        for (int i = 0; i < count; i ++) {
            View view = parentContainer.getChildAt(i);
            if (view instanceof TouchViewItem) {
                TouchViewItem item = (TouchViewItem) view;
                item.getHitRect(rectTemp);
                if (rectTemp.contains(x, y) && item.getVisibility() != View.GONE) {
                    item.setVisibility(View.GONE);
                }

                if (item.getVisibility() == View.VISIBLE) {
                    allGone = false;
                }
            }
        }

        if (allGone) {
            Log.e(TAG, "items are all gone");
            isAllItemGone = true;
            tpTestPassed();
        }

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int x,y;
        x = (int) event.getX();
        y = (int) event.getY();

        if( event.getAction() == MotionEvent.ACTION_UP ){
            return super.dispatchTouchEvent(event);
        }
        if (event.getPointerCount() == 1
                && !isAllItemGone) {

            checkTouchView(x, y);
        }

//        Log.e(TAG, "dispatchTouchEvent x = " + x + ",  y = " + y);
        return super.dispatchTouchEvent(event);
    }


    // Button
    public class TouchViewItem extends AppCompatTextView {
        public int mIndex;

        private void init(int index ){
            mIndex = index;
            this.setText(Integer.toString(index));
//            this.setTextSize((float)20.0);
            this.setTextColor(Color.BLACK);
            this.setGravity(Gravity.CENTER);
            this.setClickable(true);

            this.setBackgroundResource(R.drawable.textview_bg);
        }

        public TouchViewItem(Context context,float x, float y, int w , int h , int index ) {
            super(context);
//            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            this.setX(x);
            this.setY(y);
            this.setMinimumHeight(h);
            this.setMinimumWidth(w);
            init(index);
        }


        @Override
        public boolean performClick() {
            return super.performClick();
        }
    }

}
